<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>文件上传系统</title>
  <style>
    /* 重置表单样式 */
    body {
      font-family: Arial, sans-serif;
    }

    form {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 80%;
      margin: 50px auto;
      padding: 30px;

      background-color: white;
      box-sizing: border-box;
    }



    /* 添加用于显示文件名的新样式 */
    .file-name {
      display: block;
      margin: 0 auto;
      padding: 5px 10px;
      font-size: 14px;
      line-height: 1.5;
      word-wrap: break-word;
      /* 允许文本换行 */
      width: 100%;
      background-color: #f0f0f0;
      border-radius: inherit;
    }

    /* 为父容器添加居中对齐样式 */
    .custom-file-upload {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 150px;
      height: 40px;
      /* 根据需要调整高度 */
    }

    #progress-bar {
      width: 0;
      height: 100%;
      background-color: #00bcd4;
      border-radius: 10px;
      transition: width 0.5s;
      overflow: hidden;
      float: left;
      display: flex;
    }

    .progress-bar-box {
      width: 100%;
      height: 20px;
      margin-bottom: 10px;
      transition: width 0.5s;
      position: relative;
      overflow: hidden;
    }

    #progress-bar::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      background-color: #e0e0e0;
      border-radius: 6px;
      z-index: -1;
    }

    #status-message {
      font-size: 14px;
      color: #5c6bc0;
      margin-top: 10px;
    }

    button[type='submit'] {
      width: 100%;
      height: 48px;
      background-color: #5c6bc0;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-weight: bold;
      outline: none;
      margin-top: 20px;
      transition: background-color 0.3s;
    }

    button[type='submit']:hover {
      background-color: #5c6bc0;
    }

    .file-input {
      height: 56px;
      border-radius: 5px;
      background-color: #f0f0f0;
      position: relative;
      width: 100%;
    }

    .file-input-before {
      position: absolute;
      left: 50%;
      width: 60%;
      transform: translateX(-50%);
      top: 10px;
      font-size: 14px;
      background-color: #5c6bc0;
      color: white;
      border-radius: 5px;
      padding: 8px 25px;
      cursor: pointer;
      transition: .3s;
      font-weight: bold;
      text-align: center;
    }

    .file-input-before:hover {
      background-color: #3f51b5;
    }
  </style>
</head>

<body>
  <form id="upload-form">
    <div class="file-input">
      <div id="file-input-before" class="file-input-before">选择文件</div>
    </div>
    <input type="file" id="file-input" accept="*/*" style="display: none;" />
    <br />
    <span class="file-name">未选择文件</span>
    <br /><br />
    <div class="progress-bar-box">
      <div id="progress-bar"></div>
      <span id="progress-bar-text"></span>
      <br />
    </div>

    <span id="status-message"></span>
    <br /><br />
    <button type="submit">上传文件</button>
  </form>

  <script>
    let fileName = ''
    let successFileName = null
    let uploadFile = null
    const fileInput = document.getElementById('file-input')
    const statusMessage = document.getElementById('status-message')
    const progressBar = document.getElementById('progress-bar')
    let uploading = false
    document.getElementById('file-input-before').addEventListener('click', () => fileInput.click())
    fileInput.addEventListener('change', function () { setFileValue(this.files[0]) })
    document.addEventListener('DOMContentLoaded', function () {
      document
        .getElementById('upload-form')
        .addEventListener('submit', async (event) => {
          if (uploading) {
            return
          }
          event.preventDefault()
          if (!uploadFile) {
            statusMessage.textContent = '请选择一个文件'
            return
          }
          const _fileName = fileName
          if (successFileName === _fileName) {
            statusMessage.textContent = '上传成功，无需重新上传'
            return
          }

          const formData = new FormData()
          formData.append('multipartFile', uploadFile)
          let path = window.localStorage.getItem('path')
          if (!path || typeof path != 'string')
            path = '/'
          formData.append('path', path)
          const secretKey = localStorage.getItem('secretKey')
          if (secretKey) {
            formData.append('secretKey', secretKey)
          }
          const res = await fetch('/exists', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ path: path + '/' + _fileName }),
          }).then((res) => res.json())
          if (!res.result) {
            statusMessage.textContent = res.msg
            return
          }
          if (res.data && !(await showConfirm('文件已存在，是否覆盖？'))) return
          try {
            // 清空之前的状态信息
            progressBar.style.width = '0%'
            statusMessage.textContent = ''
            const xhr = new XMLHttpRequest()
            xhr.onreadystatechange = (e) => {
              if (xhr.readyState !== XMLHttpRequest.DONE) return
              uploading = false
              if (xhr.status !== 200) {
                statusMessage.textContent = "错误码:" + xhr.status
                return
              }
              if (xhr.responseText == '请先获取权限') {
                // window.location.href = '/login'
                window.parent.postMessage("login", "*")
                return
              }
              if (xhr.responseText === '文件上传成功！') {
                statusMessage.textContent = '上传成功！'
                successFileName = _fileName
              } else {
                statusMessage.textContent = `上传失败：${xhr.responseText}`
              }
            }
            xhr.upload.onprogress = (event) => {
              if (event.lengthComputable) {
                const percentComplete = (event.loaded / event.total) * 100
                progressBar.style.width = percentComplete.toFixed(2) + '%'
                statusMessage.textContent = percentComplete.toFixed(2) + '%'
              }
            }
            xhr.open('POST', '/up_data', true)
            xhr.send(formData)
            uploading = true
          } catch (error) {
            progressBar.style.width = '0%'
            statusMessage.textContent = '上传过程中发生错误：' + error.message
          }
        })
    })
    function showConfirm (msg) {
      let resolve
      const p = new Promise((res, rej) => { resolve = res })
      if (window.parent?.$confirm) {
        window.parent.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => { resolve(true) }).catch(() => resolve(false))
        return p
      }
      const flag = confirm(msg)
      setTimeout(() => res(flag), 10)
      return p
    }

    function clearFile () {
      if (uploadFile) {
        uploadFile = null
        fileName = ''
        statusMessage.textContent = ''
        progressBar.style.width = '0%'
        document.querySelector('.file-name').textContent = '未选择文件'
        successFileName = null
      }
    }

    function setFileValue (file) {
      if (!file) return
      if (uploading) return
      uploadFile = file
      fileName = file.name
      document.querySelector('.file-name').textContent = fileName
      statusMessage.textContent = ""
    }
    function dropEventFun (event) {
      // 阻止事件的默认行为
      event.preventDefault()
      const f = window.parent?.dropEventFun
      if (f) {
        f(event)
        return
      }

      if (event.type === 'drop') {
        const iframe = document.getElementById('upload-iframe')
        // 文件进入并松开鼠标,文件边框恢复正常
        for (let file of event.dataTransfer.files) {
          if (file.type === '' && file.size === 0)//文件夹跳过
            continue
          setFileValue(file)
        }
        window.parent?.postMessage("drop", "*")
      } else if (event.type === 'dragleave') {
        // 离开时边框恢复
        window.parent?.postMessage("dragleave", "*")
      } else {
        // 进入边框变为红色
        window.parent?.postMessage("dragleave", "*")
      }
    }
    const dropTarget = window
    dropTarget.addEventListener("dragenter", dropEventFun)
    dropTarget.addEventListener("dragover", dropEventFun)
    dropTarget.addEventListener("drop", dropEventFun)
    dropTarget.addEventListener("dragleave", dropEventFun);
  </script>

  <script>

  </script>
</body>

</html>